package com.robot.console.config;

import com.go.GlobalParam;
import com.go.logging.Logs;
import com.robot.console.core.ClientInfo;
import com.robot.console.core.ClientUtils;
import com.robot.console.util.DelaySystemExit;
import com.robot.console.util.XmlTools;
import org.jdom2.Document;
import org.jdom2.Element;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class HaConfigBuilder
{
	public static String ACCESS_LOG = "access.log";
	public static final int ANIMAL = 0;
	public static final int BOY = 1;
	public static String ERROR_LOG = "error.log";
	public static final String ETC_PATH = "etc";

	public static final String FILE_SEP = System.getProperty("file.separator");
	public static final int GIRL = 2;
	public static final String LOG_PATH = "logs";
	public static AtomicInteger robotsUserIdSequeces = new AtomicInteger(0);
	public static String VERBOSE_LOG = "verbose.log";
	private static final ArrayList<ClientInfo> clientInfoList = new ArrayList<ClientInfo>();
	private static final ArrayList<IConfig> csConfigs = new ArrayList<IConfig>();

	private static int guestSize;
	private static final ArrayList<IConfig> receiverConfigs = new ArrayList<IConfig>();
	private static final ArrayList<IConfig> senderConfigs = new ArrayList<IConfig>();
	private static int userSize;

	public static ArrayList<IConfig> getCsconfigs()
	{
		return csConfigs;
	}

	public static int getGuestSize()
	{
		return guestSize;
	}

	public static ArrayList<IConfig> getReceiverconfigs()
	{
		return receiverConfigs;
	}

	public static ArrayList<ClientInfo> getRobotinfolist()
	{
		return clientInfoList;
	}

	public static ArrayList<IConfig> getSenderconfigs()
	{
		return senderConfigs;
	}

	public static void initRootLogger()
	{
		File fp = new File(LOG_PATH);
		if (fp.exists())
		{
			boolean canWrite = fp.canWrite();
			if (!canWrite)
			{
				System.out.println("Fatal Error: Log path: " + LOG_PATH + " can't write");
				DelaySystemExit.exit();
			}
		}
		else
		{
			if (!fp.mkdir())
			{
				System.out.println("Fatal Error: Data path: " + LOG_PATH + " can't create");
				DelaySystemExit.exit();
			}
		}
		String accessLogPath = LOG_PATH + GlobalParam.PATH_SEP + ACCESS_LOG;
		String errorLogPath = LOG_PATH + GlobalParam.PATH_SEP + ERROR_LOG;
		String verboseLogPath = LOG_PATH + GlobalParam.PATH_SEP + VERBOSE_LOG;
		try
		{
			Logs.configureRootLog(GlobalParam.LOG_MODE, verboseLogPath, accessLogPath, errorLogPath);
		}
		catch (Exception e)
		{
		}
	}

	public static void loadConfig(String etcFile) throws Exception
	{
		File fp = new File(ETC_PATH + FILE_SEP + etcFile);
		Document etcDoc = XmlTools.file2Document(fp);
		Element rootElement = etcDoc.getRootElement();

		Element csElement = rootElement.getChild("connection-servers");
		if (csElement != null)
		{
			buildCsConfigs(csElement);
		}

		Element userListElement = rootElement.getChild("user-list");
		Element usersElement = userListElement.getChild("users");

		@SuppressWarnings("rawtypes")
		List userInfoList = usersElement.getChildren();
		guestSize = Integer.parseInt(userListElement.getChild("guest-size").getText());

		if (userInfoList.size() == 0)
		{
			Exception noRoomException = new Exception("No Room Info");
			throw noRoomException;
		}
		else
		{
			userSize = userInfoList.size();
			for (int i = 0; i < userSize; i++)
			{
				Element userElement = (Element) userInfoList.get(i);

				String userId = userElement.getAttribute("user-id").getValue();
				String toUserId = userElement.getAttribute("to-user-id").getValue();
				String token = userElement.getAttribute("token").getValue();

				org.jdom2.Attribute roomIdAttribute = userElement.getAttribute("room-id");
				String roomId = "";
				if (roomIdAttribute != null)
				{
					roomId = roomIdAttribute.getValue();
				}

				ClientInfo clientInfo = createClientInfo(userId, token, toUserId, roomId);
				HaConfigBuilder.clientInfoList.add(clientInfo);
			}
		}

		buildRobotInfoList();
		initRootLogger();
	}

	private static void buildCsConfigs(Element analyzerElement)
	{
		IConfig config = new CsConfig();
		config.buildConfig(analyzerElement);
		HaConfigBuilder.getCsconfigs().add(config);

	}

	private static void buildRobotInfoList()
	{
		try
		{
			for (int index = 0; index < HaConfigBuilder.guestSize; index++)
			{
				String userId = String.valueOf(HaConfigBuilder.robotsUserIdSequeces.getAndIncrement());
				String password = "1234";
				String toUserId = String.valueOf(HaConfigBuilder.robotsUserIdSequeces.get());
				if ((index + 1) == HaConfigBuilder.guestSize)
				{
					toUserId = "0";
				}
				ClientInfo robotInfo = createClientInfo(userId, password, toUserId, "0");
				HaConfigBuilder.clientInfoList.add(robotInfo);
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}

	private static ClientInfo createClientInfo(String userId, String token, String toUserId, String roomId)
	{
		ClientInfo clientInfo;
		int chance = ClientUtils.RandomNumberBuilder(3);
		int gender;

		if (chance >= 0 && chance < 2)
		{
			gender = HaConfigBuilder.BOY;

		}
		else if (chance >= 2 && chance < 4)
		{
			gender = HaConfigBuilder.GIRL;
		}
		else
		{
			gender = HaConfigBuilder.ANIMAL;
		}

		clientInfo = new ClientInfo(userId);
		clientInfo.setGender(gender);
		clientInfo.setServerIp("");
		clientInfo.setServerPort(0);
		clientInfo.setToUserId(toUserId);
		clientInfo.setDevType(CommendParams.DEV_IOS);
		clientInfo.setToken(token);
		clientInfo.setUuid("ABCD_EFG_HIJK_LMN");
		clientInfo.setRoomId(roomId);

		String roomType = "3";
		clientInfo.setRoomType(roomType);

		String talkMsg = "Hello : " + clientInfo.getToUserId();
		clientInfo.setTalkMsg(talkMsg);

		return clientInfo;
	}
}
